<template>
  <div>
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">个人奖项</span>
      </div>

      <pdf-preview :pdf-url="form.pdfUrl"></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">信息详情</span>
        </div>
        <div>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="奖项名称" prop="title" required>
              <el-input v-model="form.title" placeholder="请填写奖项名称" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="本人排名" prop="authorRank" required>
              <el-select v-model="form.authorRank" style="width: 34vw;">
                <el-option v-for="i in 13" :key="i" :label="i.toString()" :value="i"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="获奖名次" prop="awardLevel">
              <el-select v-model="form.awardLevel" placeholder="请选择获奖名次" style="width: 34vw;">
                <el-option label="一等奖" value="一等奖"></el-option>
                <el-option label="二等奖" value="二等奖"></el-option>
                <el-option label="三等奖" value="三等奖"></el-option>
                <el-option label="金" value="金"></el-option>
                <el-option label="银" value="银"></el-option>
                <el-option label="铜" value="铜"></el-option>
                <el-option label="冠" value="冠"></el-option>
                <el-option label="亚" value="亚"></el-option>
                <el-option label="季" value="季"></el-option>
                <el-option label="特等奖" value="特等奖"></el-option>
                <el-option label="优秀奖" value="优秀奖"></el-option>
                <el-option label="入围奖" value="入围奖"></el-option>
                <el-option label="优秀指导教师奖" value="优秀指导教师奖"></el-option>
                <el-option label="优秀组织奖" value="优秀组织奖"></el-option>
                <el-option label="不计等次" value="不计等次"></el-option>
                <el-option label="其它" value="其它"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="奖项级别" prop="level" required>
              <el-select v-model="form.level" placeholder="请选择奖项级别" style="width: 34vw;">
                <el-option label="国际级" value="国际级"></el-option>
                <el-option label="国家级" value="国家级"></el-option>
                <el-option label="省级" value="省级"></el-option>
                <el-option label="市厅级" value="市厅级"></el-option>
                <el-option label="校级" value="校级"></el-option>
                <el-option label="其它" value="其它"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="授予单位" prop="grantingUnit" required>
              <el-input v-model="form.grantingUnit" placeholder="请填写授予单位" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="获奖时间" prop="awardTime" required>
              <el-date-picker
                  v-model="form.awardTime"
                  type="date"
                  placeholder="选择日期"
                  style="width: 34vw;"
                  value-format="x">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="关联课题" prop="projectId">
              <el-input v-model="form.projectId" placeholder="请选择本ndnu-成果所属课题" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="作者信息" prop="authorInfo">
              <div style="background-color: #f9f9f9; width: 55vw; height: auto;">
                <ul style="display: flex; list-style-type: none; padding: 0; margin: 0; line-height: 6vh; color: #3f3f3f">
                  <li style="margin-left: 1.5vw">排序</li>
                  <li style="margin-left: 3vw">姓名</li>
                  <li style="margin-left: 3.5vw">作者身份</li>
                  <li style="margin-left: 3.5vw">单位名称</li>

                </ul>
                <div v-for="(author, index) in form.authorInfo" :key="index" style="margin-top: 1vh; display: flex; align-items: center;">
                  <el-select v-model="author.rank" placeholder="排序" style="width: 4vw;">
                    <el-option
                        v-for="i in 13"
                        :key="i"
                        :label="i.toString()"
                        :value="i">
                    </el-option>
                  </el-select>
                  <el-input v-model="author.name" placeholder="姓名" style="width: 5vw; margin-left: 1vw"></el-input>
                  <el-select v-model="author.identity" placeholder="身份" style="width: 5.5vw; margin-left: 1vw">
                    <el-option label="老师" value="老师"></el-option>
                    <el-option label="博士生" value="博士生"></el-option>
                    <el-option label="硕士生" value="硕士生"></el-option>
                    <el-option label="本科生" value="本科生"></el-option>
                    <el-option label="其它" value="其它"></el-option>
                  </el-select>
                  <el-input v-model="author.institution" placeholder="单位名称" style="width: 15vw; margin-left: 1vw"></el-input>

                </div>
              </div>
            </el-form-item>
            <el-form-item label="备注信息" prop="remarks">
              <el-input type="textarea" :rows="4" v-model="form.remarks" placeholder="请输入备注信息" style="width: 34vw;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submit" class="upload-button" style="width: 10vw;">返回</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { getPersonalAwardById } from "@/api/result/awardPersonal.js";
import { getProjectNameById } from "@/api/result/longitudinalProjects";
import PdfPreview from "@/components/result/PdfPreview.vue";


const router = useRouter()
const route = useRoute()
const formRef = ref(null)

const form = reactive({
  id: '',
  title: '',
  authorRank: null,
  awardLevel: '',
  level: '',
  grantingUnit: '',
  awardTime: '',
  remarks: '',
  projectId: '', // 存储课题ID或名称
  authorInfo: [{
    rank: 1,
    name: '',
    identity: '',
    institution: '',
    corresponding: false,
    coFirstAuthor: false
  }],
  syncStatus: '',
  pdfUrl: '' // 修复：原代码中PDF预览绑定的是pdfUrl，但form里定义的是pdfPath，此处统一为pdfUrl
})

const rules = {
  title: [{ required: true, message: '请输入奖项名称', trigger: 'blur' }],
  authorRank: [{ required: true, message: '请选择本人排名', trigger: 'change' }],
  level: [{ required: true, message: '请选择奖项级别', trigger: 'change' }],
  grantingUnit: [{ required: true, message: '请输入授予单位', trigger: 'blur' }],
  awardTime: [{ required: true, message: '请选择获奖时间', trigger: 'change' }]
}

const addAuthor = () => {
  form.authorInfo.push({
    rank: form.authorInfo.length + 1,
    name: '',
    identity: '',
    institution: '',
    corresponding: false,
    coFirstAuthor: false
  })
}

const removeAuthor = (index) => {
  form.authorInfo.splice(index, 1)
}

const submit = async () => {
  router.push("/result/awardPersonal");
}

// 安全转换日期为时间戳（解决时间不显示问题）
const parseDateToTimestamp = (dateValue) => {
  if (!dateValue) return null;
  // 处理字符串格式日期（如"2025-08-13"）
  if (typeof dateValue === 'string') {
    const date = new Date(dateValue);
    return date.getTime(); // 转换为毫秒时间戳
  }
  // 处理数字类型时间戳（确保是毫秒级）
  if (typeof dateValue === 'number') {
    // 如果是秒级时间戳（长度10位），转换为毫秒级（长度13位）
    if (dateValue.toString().length === 10) {
      return dateValue * 1000;
    }
    return dateValue;
  }
  return null;
}

onMounted(async () => {
  const id = route.query.id;
  if (id) {
    try {
      // 获取个人奖项信息
      const res = await getPersonalAwardById(id);
      if (res.code === 200 && res.data) {
        const data = res.data;

        // 重点修复：处理获奖时间，确保日期选择器能正确显示
        data.awardTime = parseDateToTimestamp(data.awardTime);

        // 填充个人奖项信息
        Object.assign(form, data);
        // 修复PDF路径字段不一致问题
        if (data.pdfPath && !form.pdfUrl) {
          form.pdfUrl = data.pdfPath;
        }


      } else {
        ElMessage.error(`获取个人奖项信息失败：${res.msg || '未知错误'}`);
      }
    } catch (error) {
      console.error('获取个人奖项信息失败:', error);
      ElMessage.error('加载个人奖项数据时发生错误，请重试');
    }
  }
});

</script>

<style scoped>
.upload-button {
  color: white;
  height: 3.8vh;
  width: 6.5vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
}

.upload-button:hover {
  background-color: #009b77;
}

canvas {
  display: block;
  margin: 0 auto;
  background: white;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  transform-origin: top center;
}
</style>
